package cn.pconline.autoclub.service.bbssync;

import org.springframework.beans.factory.annotation.Autowired;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.OMemberService;

import com.alibaba.fastjson.JSONObject;
import java.util.List;

/**
 * @author zhouruxuan
 * @date 2014年12月4日 下午12:10:15
 */
public class SyncSetUserVipService extends BbsSyncPetrolService {

    @Autowired
    private OMemberService oMemberService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private OClubService oClubService;

    @Override
    protected int addPetroltoMember(ClubMember clubMember, JSONObject msg) {
        log.info("set vip user need not add petrol to member");
        return 0;
    }

    @Override
    protected int addPetroltoClub(Club club, JSONObject msg) {
        ClubIntegral integral = petrolService
                .getById(PetrolService.ADD_CLUB_PETROL_ITEM_VIP);
        String reason = integral.getName() + "(userId-" + getUserId(msg) + ")";
        petrolService.addToClubWithinLimit(club.getClubId(), integral.getIntegralId(), integral.getPetrol(), reason, false);
        return integral.getPetrol();
    }

    @Override
    protected long getUserId(JSONObject msg) {
        return msg.getLongValue("userId");
    }

    @Override
    public void process(JSONObject msg, ClubMember clubMember) {

        // 验证用户
        long userId = getUserId(msg);
        if (userId <= 0L) {
            log.warn("not userId-{}", userId);
            return;
        }

        //判断用户是否登录
        User user = userService.authUser(userId);
        if (user == null || user.getUid() == 0L) {
            log.warn("not found user-{}", userId);
            return;
        }
        userService.setVip(user, msg.getString("vipInfo"));
        if (clubMember != null) {
            clubService.increaseVipNum(clubMember.getClubId());
        }
        //更新品牌车友会认证人数
         List<OClub> list = oClubService.listClub4Join(user.getUid());
            for (OClub c : list) {
                int vipNum = oMemberService.countVipMember(c.getoClubId()) + 1;
                oClubService.updateVipNum(c.getoClubId(), vipNum);
            }
    }
}
